'use strict';
const mongoose = require('mongoose');
// const OssHelper = require('./../../util/OSSHelper');
// OssHelper.init(require('./../../config').oss);

module.exports = {
    async add(options){
        console.log('options ==', options);
        let FriendlyLinkModel = mongoose.models['FriendlyLink'];
        let res = /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/.test(options.name);
        if(!res){
            throw new Error("该链接名字格式不正确");
        }
        let result = await FriendlyLinkModel.findOne({name: options.name});
        if(result){
            throw new Error("该链接名字已存在")
        }
        // let imgUrl = await OssHelper.upload('./public/1.png', options.imgUrl);
        await FriendlyLinkModel.create(options);
    },
    async delete(options){
        let FriendlyLinkModel = mongoose.models['FriendlyLink'];
        await FriendlyLinkModel.remove({_id: options._id.toString()});
    },
    async edit(options){
        let FriendlyLinkModel = mongoose.models['FriendlyLink'];
        let friendlyLink = await FriendlyLinkModel.findOne({_id: options._id.toString()});
        if(!friendlyLink){
            throw new Error("修改的链接不存在");
        }
        let res = /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/.test(options.name);
        if(!res){
            throw new Error("该链接名字格式不正确");
        }
        let data = await FriendlyLinkModel.findOne({_id: {$ne: friendlyLink._id.toString()}, name: options.name});
        if(data){
            throw new Error("修改的链接名字已存在");
        }
        // let imgUrl = await OssHelper.upload('./public/1.png', options.imgUrl);
        delete options._id;
        await FriendlyLinkModel.update({_id: friendlyLink._id.toString()}, options);
    },
    async find(options){
        let FriendlyLinkModel = mongoose.models['FriendlyLink'];
        let friendlyLinks = await FriendlyLinkModel.find({});
        return friendlyLinks;
    }
};